<template>
  <div>
    <van-nav-bar fixed title="地址列表" left-arrow @click-left="$router.go(-1)" />
      <div class="address">
        <van-address-list
          v-model="chosenAddressId"
          :list="updateAddress"
          :disabled-list="disabledList"
          disabled-text="以下地址超出配送范围"
          default-tag-text="默认地址"
          @add="onAdd"
          @edit="onEdit"
          @select="onSelect"
        />
      </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'addressList',
  data () {
    return {
      chosenAddressId: this.$store.state.address.defaultAddress,
      disabledList: [
        {
          id: '3',
          name: '王五',
          tel: '1320000000',
          address: '浙江省杭州市滨江区江南大道 15 号'
        }
      ]
    }
  },
  async created () {
    // 获取地址列表
    this.getAddressList()
    // 默认收货地址
    this.setDefaultAddress()
  },
  computed: {
    ...mapState('address', ['addressList', 'defaultAddress']),
    // 将地址列表的数据处理
    updateAddress () {
      return this.addressList.map(item => {
        return {
          id: item.address_id,
          name: item.name,
          tel: item.phone,
          address: `${item.region.province} ${item.region.city} ${item.region.region} ${item.detail}`,
          isDefault: item.address_id === this.defaultAddress
        }
      })
    }

  },
  methods: {
    // 渲染地址列表
    getAddressList () {
      this.$store.dispatch('address/getAddressList')
    },
    // 默认地址
    setDefaultAddress () {
      this.$store.dispatch('address/setDefaultAddress')
    },
    // 选择地址
    onSelect (item) {
      // console.log(item)
      item.isDefault = true
    },
    // 新增地址
    onAdd () {
      this.$toast('新增地址')
      this.$router.push('/addressedit')
    },
    // 编辑地址
    onEdit (item, index) {
      console.log(item)
      this.$router.push(`/addressedit?addressId=${item.id}`)
      this.$toast('编辑地址:' + index)
    }
  }
}
</script>

<style lang="less" scoped>
.address {
  padding-top: 46px;
}

</style>
